import { ref } from 'vue'
import store from '../store/store.js'
import router from "../router/router.js";
import {getGamePetsPick, getGameStateSymmetry, getGameStateUnilateral} from "./banpickCall.js";

let ws;

export const isConnect = ref()

// 心跳间隔
const timeout = 1000 * 10;
// 延时发送消息对象（启动心跳新建这个对象，收到消息后重置对象）
let timeoutObj = null;
export function heartBeat() {
    // 心跳检测
    // console.log("heartbeat")
    clearTimeout(timeoutObj);
    timeoutObj = setTimeout(function () {
        if (isConnect.value) {
            ws.send("heartbeat");
        }
    }, timeout);
}

export function connect() {
    let token = localStorage.getItem('token');
    if (!token) {
        router.push({name: 'Hall'});
        return;
    }
    if (!isConnect.value) {
        // ws = new WebSocket(`ws://${window.location.hostname}:8000/game/connection?token=${token}`);
        ws = new WebSocket(`ws://${window.location.hostname}:${window.location.port}/game/connection?token=${token}`);
    }
    ws.onopen = function () {
        isConnect.value = true;
        console.log("connected!");
        heartBeat();
    }
    ws.onerror = function (e) {
        isConnect.value = false;

        console.log("connection error because");
        console.log(e)
        //连接错误 需要重连
        // relinkGame();
    }
    ws.onmessage = function (e) {
        // console.log(e.data);
        heartBeat();

        let mess = JSON.parse(e.data);
        /*
        mess: {
            event: string,
            data: any
        }
         */
        if (mess.event === "joinGame") {
            // 有人加入游戏刷新数据
            getGameStateUnilateral().then(r => {})
            getGameStateSymmetry().then(r => {})
        } else if (mess.event === "exitGame") {
            // 有人退出游戏刷新数据
            getGameStateUnilateral().then(r => {})
            getGameStateSymmetry().then(r => {})
        } else if (mess.event === "closeGame") {
            router.push({name: 'Hall'}).then(r => {});
        } else if (mess.event === "ready") {
            // 有人准备刷新数据
            getGameStateUnilateral().then(r => {})
            getGameStateSymmetry().then(r => {})
        } else if (mess.event === "allReady") {
            // 所有人准备刷新数据
            getGameStateUnilateral().then(r => {})
            getGameStateSymmetry().then(r => {})
        } else if (mess.event === "nextPhase") {
            // 进入下一个阶段，刷新数据
            getGameStateUnilateral().then(r => {})
            getGameStateSymmetry().then(r => {})
            getGamePetsPick().then(r => {})
        } else if (mess.event === "typeRoll") {
            // 选手重随属系刷新数据
            getGamePetsPick().then(r => {})
            store.commit('setEventSignal')
            getGameStateUnilateral().then(r => {})
            getGameStateSymmetry().then(r => {})
        } else if (mess.event === "banpickOver") {
            getGameStateUnilateral().then(r => {})
            getGameStateSymmetry().then(r => {})
            getGamePetsPick().then(r => {})
            store.commit('setEventSignal')
        }
    }
    ws.onclose = e=> {
        console.log(e)
        isConnect.value = false;
        if (e.code === 1006) {
            router.push({name: 'Hall'})
            return
        }
        if (e.code === 1000) {
            router.push({name: 'Hall'})
            return
        }
        //连接错误 需要重连
        relinkGame();
        console.log("connection closed (" + e.code + ")");
    }
}

function relinkGame() {
    // 重连机制
    console.log("尝试重新连接");
    //如果已经连上就不在重连了
    if (isConnect.value) {
        return;
    }
    clearTimeout(timeoutObj);
    // 延迟5秒重连  避免过多次过频繁请求重连
    timeoutObj = setTimeout(function () {
        connect();
    }, 5000);
}

export function close() {
    ws.close();
}